<template>
    <div class="app-container">
        <el-form :model="queryParams" ref="queryRef" :inline="true" label-width="120px" v-show="showSearch">
            <el-form-item label="报告类型" prop="rtType">
                <el-select v-model="queryParams.rtType" placeholder="请选择报告类型" clearable>
                    <el-option v-for="item in optionType" :key="item.value" :label="item.label" :value="item.value">
                    </el-option>
                </el-select>
            </el-form-item>
            <el-form-item label="上传人" prop="rtPepole">
                <el-input v-model="queryParams.rtPepole" placeholder="请输入上传人"  clearable />
            </el-form-item>
            <el-form-item label="上传日期" prop="time">
                <el-date-picker v-model="queryParams.time" value-format="YYYY-MM-DD HH:mm:ss" type="daterange" range-separator="至" start-placeholder="开始日期"
                    end-placeholder="结束日期" />
            </el-form-item>
            <el-form-item>
                <el-button type="primary" @click="handleQuery">搜索</el-button>
                <el-button @click="resetQuery">重置</el-button>
            </el-form-item>
        </el-form>

        <el-row :gutter="10" class="mb8">
            <el-col :span="1.5">
                <el-button type="primary" @click="handleUpload" v-if="permission">
                    <svg-icon class-name="upload-icon" icon-class="upload" /><span style="margin-left:10px">上传</span>
                </el-button>
            </el-col>
            <el-col :span="1.5">
                <el-button type="primary" icon="Delete" :disabled="multiple" @click="handleDelete" v-if="permission">删除</el-button>
            </el-col>
            <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>

        <el-table v-loading="loading" :data="dataList" stripe @selection-change="handleSelectionChange" row-key="rtId">
            <el-table-column type="selection" width="55" align="center" :reserve-selection="true" />
            <el-table-column label="报告名称" align="center" prop="rtName" width="255" show-overflow-tooltip />
            <el-table-column label="报告类型" align="center" prop="rtType">
                <template #default="scope">
                    <span v-if="scope.row.rtType=='0'">地震环境及监测能力分析</span>
                    <span v-if="scope.row.rtType=='1'">房屋地震灾害分析评估</span>
                    <span v-if="scope.row.rtType=='2'">地震灾害风险排查及建议</span>
                </template>
            </el-table-column>
            <el-table-column label="上传人" align="center" prop="rtPepole" />
            <el-table-column label="上传日期" align="center" prop="rtTime" />
            <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
                <template #default="scope">
                    <el-button type="text" @click="handleDown(scope.row)">下载</el-button>
					<el-button type="text" @click="handleDelete(scope.row)" v-if="permission">删除</el-button>
                </template>
            </el-table-column>
        </el-table>

        <pagination v-show="total > 0" :total="total" v-model:page="queryParams.page" v-model:limit="queryParams.rows"
            @pagination="getList" />

        <el-dialog title="报告管理" v-model="openFile" width="700px" top="200px" append-to-body>
            <el-form ref="bgmbRef" label-width="120px" :model="form" :rules="rules" >
                <el-row style="margin: 20px 0;">
                    <el-col class="tab-title">地震环境及监测能力分析</el-col>
                    <el-col>
                        <el-form-item label=""  prop="attachId1">
                            <file-upload :action="uploadFileUrl" :limit="1" ref="fileUpload1" v-model="form.fileList1" :fileSize="100" @uploadFile="uploadFile" @delFile="delFile"
                                :fileType='["doc", "docx"]' />
                        </el-form-item>
                    </el-col>
                    <el-col>
                        <el-form-item label=""  prop="reportName1">
                            <el-input v-model="form.reportName1" placeholder="请输入报告名称" :disabled="reportNameRule1"  clearable />
                        </el-form-item>
                    </el-col>
                    <el-col class="tab-title">房屋地震灾害分析评估</el-col>
                    <el-col>
                        <el-form-item label=""  prop="attachId2">
                            <file-upload :action="uploadFileUrl" :limit="1" ref="fileUpload2" v-model="form.fileList2" :fileSize="100" @uploadFile="uploadFile" @delFile="delFile"
                                :fileType='["doc", "docx"]' />
                        </el-form-item>
                    </el-col>
                    <el-col>
                        <el-form-item label=""  prop="reportName2">
                            <el-input v-model="form.reportName2" placeholder="请输入报告名称" :disabled="reportNameRule2"  clearable />
                        </el-form-item>
                    </el-col>
                    <el-col class="tab-title">地震灾害风险排查及建议</el-col>
                    <el-col>
                        <el-form-item label=""  prop="attachId3">
                            <file-upload :action="uploadFileUrl" :limit="1" ref="fileUpload3" v-model="form.fileList3" :fileSize="100" @uploadFile="uploadFile" @delFile="delFile"
                                :fileType='["doc", "docx"]' />
                        </el-form-item>
                    </el-col>
                    <el-col>
                        <el-form-item label=""  prop="reportName3">
                            <el-input v-model="form.reportName3" placeholder="请输入报告名称" :disabled="reportNameRule3" clearable />
                        </el-form-item>
                    </el-col>
                </el-row>
            </el-form>
            <template #footer>
                <div class="dialog-footer">
                    <el-button type="primary" @click="fileSubmitForm">保 存</el-button>
                    <el-button @click="openFile = false">取 消</el-button>
                </div>
            </template>
        </el-dialog>
    </div>
</template>
  
<script setup name="reportModule">
import { getAllList , saveReportTemplate ,delReportTemplate, getPermission,checkRepeat} from "@/api/resultsReportImg/reportModule.js"
const { proxy } = getCurrentInstance();
const dataList = ref([]);
const ids = ref();
const loading = ref(false);
const single = ref(true);
const multiple = ref(true);
const permission = ref(true);
const total = ref(0);
const showSearch = ref(true);
const optionType = [{ label: '地震环境及监测能力分析', value: '0' }, { label: '房屋地震灾害分析评估', value: '1' }, { label: '地震灾害风险排查及建议', value: '2' }]
const openFile = ref(false);
const uploadFileUrl = ref(
    import.meta.env.VITE_APP_BASE_API + "/attachment/uploadFile"
); // 上传的图片服务器地址

const titleName = (rule, value, callback) => {
  if (!value&&!form.value.attachId1) {
    callback()
  }else if(!value&&form.value.attachId1){
    callback(new Error("请输入报告名称！！"))
  }else if (value && form.value.attachId1) {
    const parmas = { 
        type: '0',
        name: value }
    checkRepeat(parmas).then(res => {
      if (!res.data) {
        callback()
      } else {
        callback(new Error("该名称已存在，请重新输入"))
      }
    }).catch(_ => {
      callback(new Error(_.message))
    })
  }
}

const titleName1 = (rule, value, callback) => {
  if (!value&&!form.value.attachId2) {
    callback()
  }else if(!value&&form.value.attachId2){
    callback(new Error("请输入报告名称！！"))
  }else if (value && form.value.attachId2) {
    const parmas = { 
        type: '1',
        name: value }
    checkRepeat(parmas).then(res => {
      if (!res.data) {
        callback()
      } else {
        callback(new Error("该名称已存在，请重新输入"))
      }
    }).catch(_ => {
      callback(new Error(_.message))
    })
  }
}

const titleName2 = (rule, value, callback) => {
  if (!value&&!form.value.attachId3) {
    callback()
  }else if(!value&&form.value.attachId3){
    callback(new Error("请输入报告名称！！"))
  }else if (value && form.value.attachId3) {
    const parmas = { 
        type: '2',
        name: value }
    checkRepeat(parmas).then(res => {
      if (!res.data) {
        callback()
      } else {
        callback(new Error("该名称已存在，请重新输入"))
      }
    }).catch(_ => {
      callback(new Error(_.message))
    })
  }
}
const data = reactive({
    queryParams: {
        page: 1,
        rows: 10,
        rtPepole: undefined,
        rtType: undefined,
        time:undefined,
    },
    form: {
        fileList1: [],
        attachId1: '',
        reportName1:'',
        fileList2: [],
        attachId2: '',
        reportName2:'',
        fileList3: [],
        attachId3: '',
        reportName3:'',
    },
    rules: {
        reportName1: [{ trigger: "blur",validator: titleName, }],
        reportName2: [{ trigger: "blur" ,validator: titleName1,}],
        reportName3: [{ trigger: "blur",validator: titleName2, }],
    }
})
const { queryParams, form, rules } = toRefs(data);

/** 搜索按钮操作 */
function handleQuery() {
    queryParams.value.page = 1;
    getList();
}

/** 重置按钮操作 */
function resetQuery() {
    dataList.value = [];
    proxy.resetForm("queryRef");
    handleQuery();
}

/** 查询数据列表 */
function getList() {
    loading.value = true;
    getAllList({...queryParams.value,rtStartTime:queryParams.value.time?queryParams.value.time[0]:undefined,rtEndTime:queryParams.value.time?queryParams.value.time[1]:undefined}).then(response => {
        dataList.value = response.data.rows ? response.data.rows : [];
        total.value = response.data.total;
        loading.value = false;
    });
}

// 多选框选中数据
function handleSelectionChange(selection) {
    ids.value = selection.map(item => item.rtId);
    single.value = selection.length != 1;
    multiple.value = !selection.length;
}

/** 删除按钮操作 */
function handleDelete(row) {
    const id = row.rtId || ids.value;
    proxy.$modal.confirm('是否确认删除选中报告的数据项?').then(function () {
        return delReportTemplate(id);
    }).then(() => {
        getList();
        proxy.$modal.msgSuccess("删除成功");
    }).catch(() => { });
}

function chooseRadio(value) {
    console.log(value)
}
// 上传 
function handleUpload() {
    openFile.value = true;
    form.value =  {
        fileList1: [],
        attachId1: '',
        reportName1:'',
        fileList2: [],
        attachId2: '',
        reportName2:'',
        fileList3: [],
        attachId3: '',
        reportName3:'',
    },
    proxy.resetForm("bgmbRef");
}

//处理附件格式
function eachFiles(fileName) {
    let deepFile = JSON.parse(JSON.stringify(proxy.$refs[fileName].fileList))
    let Ids = []
    for (var i = 0; i < deepFile.length; i++) {
        Ids.push(deepFile[i].attachId)
    }
    return Ids.join(",");
}
const reportNameRule1 = ref(true);
const reportNameRule2 = ref(true);
const reportNameRule3 = ref(true);
const uploadFile = (file) => {
  if(proxy.$refs["fileUpload1"].fileList.length!=0){
        form.value.fileList1 = proxy.$refs["fileUpload1"].fileList;
        form.value.attachId1 = form.value.fileList1[0].attachId;
        if(form.value.attachId1){
            reportNameRule1.value = false;
            proxy.$refs.bgmbRef.validateField('reportName1')
        }
    }
    if(proxy.$refs["fileUpload2"].fileList.length!=0){
        form.value.fileList2 = proxy.$refs["fileUpload2"].fileList;
        form.value.attachId2 = form.value.fileList2[0].attachId;
        if(form.value.attachId2){
            reportNameRule2.value = false;
            proxy.$refs.bgmbRef.validateField('reportName2')
        }
    }
    if(proxy.$refs["fileUpload3"].fileList.length!=0){
        form.value.fileList3 = proxy.$refs["fileUpload3"].fileList;
        form.value.attachId3 = form.value.fileList3[0].attachId;
        if(form.value.attachId3){
            reportNameRule3.value = false;
            proxy.$refs.bgmbRef.validateField('reportName3')
        }
    }

    console.log(form.value.attachId1,'1',form.value.fileList1);
    console.log(form.value.attachId2,'2',form.value.fileList2);
    console.log(form.value.attachId3,'3',form.value.fileList3);
}
const delFile = (index) => {
    if(proxy.$refs["fileUpload1"].fileList.length==0){
        form.value.fileList1 = [];
        form.value.attachId1 = '';
        form.value.reportName1 = '';
        reportNameRule1.value = true;
        proxy.$refs.bgmbRef.clearValidate('reportName1')
    }else if(proxy.$refs["fileUpload2"].fileList.length==0){
        form.value.fileList2 = [];
        form.value.attachId2 = '';
        form.value.reportName2 = '';
        reportNameRule2.value = true;
        proxy.$refs.bgmbRef.clearValidate('reportName2')
    }else if(proxy.$refs["fileUpload3"].fileList.length==0){
        form.value.fileList3 = [];
        form.value.attachId3 = '';
        form.value.reportName3 = '';
        reportNameRule3.value = true;
        proxy.$refs.bgmbRef.clearValidate('reportName3')
    }
}

function fileSubmitForm() {
    // form.value.attachId1 = eachFiles('fileUpload1');
    // form.value.attachId2 = eachFiles('fileUpload2');
    // form.value.attachId3 = eachFiles('fileUpload3');
    // proxy.$refs.bgmbRef.validateField('reportName1')
    // proxy.$refs.bgmbRef.validateField('reportName2')
    // proxy.$refs.bgmbRef.validateField('reportName3')
    proxy.$refs["bgmbRef"].validate(valid => {
    if (valid) {
        const query = [
        {id:form.value.attachId1?form.value.attachId1:'',name:form.value.reportName1?form.value.reportName1:'',type:'0'},
        {id:form.value.attachId2?form.value.attachId2:'',name:form.value.reportName2?form.value.reportName2:'',type:'1'},
        {id:form.value.attachId3?form.value.attachId3:'',name:form.value.reportName3?form.value.reportName3:'',type:'2'},
        ].filter(item=>item.id)
        saveReportTemplate(query).then(res=>{
        proxy.$modal.msgSuccess("上传成功");
        openFile.value = false;
        getList();
    })
    }
})
}

// 单个下载文件
function handleDown(row) {
    var query = {
        attachId: row.attId,
        name: row.rtName
    }
    location.href = import.meta.env.VITE_APP_BASE_API + "/attachment/downLoadFile?attachId=" + encodeURIComponent(query.attachId);
}

function getPermissionAdmin(){
    getPermission().then(res=>{
        permission.value = res.data.isAdmin;
    })
}
getPermissionAdmin();
getList();
</script>
<style lang="scss" scoped>
.tab-title {
    font-size: 16px;
    font-weight: bold;
    border-left: 4px solid #0D9AFF;
    font-family: PingFangSC-Medium;
    padding-left: 10px;
    margin-bottom: 20px;
}
</style>